package searchtab.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.texteditor.ITextEditor;

import searchtab.util.SearchTabUtils;
import searchtab.views.SearchTabView;

public class ViewTabAction extends Action implements IWorkbenchWindowActionDelegate {

    private IWorkbenchWindow fWindow;

    public ViewTabAction() {
    }

    public void dispose() {
        fWindow = null;
    }

    public void init(IWorkbenchWindow window) {
        fWindow = window;
    }

    public void run(IAction iaction) {

        if (fWindow.getActivePage() == null) {
            return;
        }
        try {
            IViewPart view = fWindow.getActivePage().findView(SearchTabView.ID);
            if (view != null) {
                fWindow.getActivePage().activate(view);
            } else {
                view = fWindow.getActivePage().showView(SearchTabView.ID);
            }
            setFilter(((SearchTabView) view).getFilterControl());
        } catch (PartInitException e) {
            e.printStackTrace();
        }
    }

    public void selectionChanged(IAction iaction, ISelection iselection) {
        // do nothing since the action isn't selection dependent.

    }

    private void setFilter(Text text) {

        ITextEditor editor = SearchTabUtils.getEditor();
        if (editor == null) {
            return;
        }
        ISelectionProvider selectionProvider = editor.getSelectionProvider();

        if (selectionProvider != null && selectionProvider.getSelection() instanceof TextSelection) {

            String selectedText = ((TextSelection) selectionProvider.getSelection()).getText();
            if (selectedText != null && selectedText.length() > 0) {
                int ix = selectedText.indexOf('\n');
                if (ix > -1) {
                    selectedText = selectedText.substring(0, ix);
                }
                text.setText(selectedText);
            }
        }

    }

}
